<template>
  <div class="image-generate-container">
    <el-page-header content="AI图片生成" />

    <!-- 生成表单区域 -->
    <el-card shadow="hover" class="form-card">
      <div class="card-title">生成参数</div>
      <el-form
        ref="generateFormRef"
        :model="generateForm"
        :rules="formRules"
        label-width="100px"
        class="generate-form"
        size="medium"
      >
        <!-- 图片描述 - 仅保留必要字段 -->
        <el-form-item label="图片描述" prop="prompt">
          <el-input
            v-model="generateForm.prompt"
            type="textarea"
            placeholder="请输入详细描述（如：雪山下的木屋，冬季，卡通风格）"
            rows="4"
            maxLength="500"
            show-word-limit
            resize="none"
          />
          <div class="prompt-hint">
            描述越详细，生成效果越好。建议包含场景、风格、主体等信息
          </div>
        </el-form-item>

        <!-- 操作按钮 -->
        <el-form-item class="form-actions">
          <el-button 
            type="primary" 
            @click="handleGenerate" 
            :loading="isLoading"
            size="default"
          >
            {{ isLoading ? '生成中...' : '生成图片' }}
          </el-button>
          <el-button 
            @click="handleReset" 
            :disabled="isLoading || (!generateForm.prompt && !imageUrl)"
            class="reset-btn"
          >
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 图片预览区域 -->
    <el-card 
      shadow="hover" 
      class="preview-card"
    >
      <template #header>
        <div class="card-header">
          <span class="header-title">图片预览</span>
          <el-button 
            type="primary" 
            size="small" 
            @click="handleDownload"
            :disabled="!imageUrl"
            class="download-btn"
          >
            下载图片
          </el-button>
        </div>
      </template>
      <div class="preview-container">
        <!-- 空状态 -->
        <div class="empty-state" v-if="!imageUrl && !isLoading">
          <el-empty description="暂无生成图片" />
        </div>
        
        <!-- 加载状态 -->
        <div class="loading-state" v-if="isLoading">
          <el-skeleton style="width: 100%; height: 300px;" animated>
            <template #template>
              <el-skeleton-item variant="image" style="width: 100%; height: 300px;" />
            </template>
          </el-skeleton>
          <p class="loading-text">AI正在创作中，请稍候...</p>
        </div>
        
        <!-- 图片展示 -->
        <el-image
          v-show="imageUrl && !isLoading"
          :src="imageUrl"
          alt="生成的图片"
          class="preview-image"
          fit="contain"
          :preview-src-list="[imageUrl]"
          :preview-teleported="true"
        >
          <template #placeholder>
            <div class="image-slot">
              <el-skeleton style="width: 100%; height: 300px;">
                <template #template>
                  <el-skeleton-item variant="image" style="width: 100%; height: 300px;" />
                </template>
              </el-skeleton>
            </div>
          </template>
          <template #error>
            <div class="image-slot">
              <el-empty description="图片加载失败" />
            </div>
          </template>
        </el-image>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage, ElLoading, ElForm, ElSkeleton, ElSkeletonItem } from 'element-plus'
import { generateImage } from '@/api/image/imageGenerate'

// 修复：将 ref(ElForm) 改为 ref(null)
const generateFormRef = ref(null)
const isLoading = ref(false)
const imageUrl = ref('') // 改为单个图片URL

// 表单数据 - 仅保留prompt字段
const generateForm = reactive({
  prompt: ''
})

// 校验规则 - 仅保留对prompt的验证
const formRules = reactive({
  prompt: [
    { required: true, message: '请输入图片描述', trigger: 'blur' },
    { min: 1, max: 500, message: '描述长度应在1-500个字符之间', trigger: 'blur' }
  ]
})

/**
 * 生成图片 - 适配后端接口
 */
const handleGenerate = async () => {
  // 修复：添加表单引用检查
  if (!generateFormRef.value) return
  
  const valid = await generateFormRef.value.validate().catch(() => false)
  if (!valid) return

  // 仅传递prompt参数，符合后端接口要求
  const requestData = {
    prompt: generateForm.prompt.trim()
  }

  try {
    isLoading.value = true
    imageUrl.value = '' // 清空之前的图片
    
    // 显示全局加载提示
    const loading = ElLoading.service({ 
      text: 'AI正在创作中...', 
      lock: true,
      background: 'rgba(255, 255, 255, 0.7)'
    })
    
    // 调用API
    const res = await generateImage(requestData)
    if (res.code === 200 && res.data) {
      imageUrl.value = res.data // 后端直接返回图片URL字符串
      ElMessage.success('图片生成成功！')
    } else {
      ElMessage.error('生成失败：' + (res.msg || '未知错误'))
    }
  } catch (err) {
    console.error('请求异常：', err)
    ElMessage.error('请求异常，请重试！')
  } finally {
    isLoading.value = false
    ElLoading.service().close()
  }
}

/**
 * 重置表单
 */
const handleReset = () => {
  // 添加表单引用检查
  if (!generateFormRef.value) return
  
  generateFormRef.value.resetFields()
  imageUrl.value = '' // 清空图片
}

/**
 * 下载图片
 */
const handleDownload = async () => {
  if (!imageUrl.value) return
  
  try {
    // 创建下载链接
    const link = document.createElement('a')
    link.href = imageUrl.value
    link.download = `AI生成图片_${new Date().getTime()}.png`
    link.style.display = 'none'
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    ElMessage.success('图片下载成功！')
  } catch (err) {
    console.error('下载失败：', err)
    ElMessage.error('下载失败，请右键图片另存为')
  }
}
</script>

<style scoped>
.image-generate-container { 
  padding: 24px; 
  max-width: 1200px;
  margin: 0 auto;
}

.card-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 20px;
}

.form-card { 
  margin-bottom: 24px; 
  border: none;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.generate-form { 
  margin-top: 15px; 
}

.prompt-hint {
  margin-top: 8px;
  padding: 8px 12px;
  background-color: #f5f7fa;
  border-radius: 4px;
  font-size: 12px;
  color: #909399;
}

.form-actions {
  margin-top: 20px;
}

.reset-btn {
  margin-left: 12px;
}

.preview-card { 
  margin-top: 20px; 
  border: none;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header { 
  display: flex; 
  justify-content: space-between; 
  align-items: center; 
}

.header-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.download-btn {
  padding: 8px 16px;
}

.preview-container { 
  display: flex; 
  justify-content: center; 
  padding: 20px;
  min-height: 300px;
  align-items: center;
}

.preview-image { 
  max-width: 100%; 
  max-height: 500px; 
}

.empty-state,
.loading-state {
  width: 100%;
  text-align: center;
}

.loading-state .loading-text {
  margin-top: 16px;
  color: #909399;
  font-size: 14px;
}

:deep(.image-slot) {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  min-height: 300px;
}
</style>